package com.jmb.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jmb.api.common.exception.LeaseException;
import com.jmb.api.common.result.ResultCodeEnum;
import com.jmb.api.mapper.ApiCaseSuiteCaseRefMapper;
import com.jmb.api.mapper.TaskMapper;
import com.jmb.api.model.entity.ApiCaseSuite;
import com.jmb.api.model.entity.ApiCaseSuiteCaseRef;
import com.jmb.api.model.entity.ApiCaseSuiteProcessor;
import com.jmb.api.model.to.api.suite.ApiCaseSuiteCaseRefTO;
import com.jmb.api.model.to.api.suite.ApiCaseSuiteInfoTO;
import com.jmb.api.model.to.api.suite.ApiCaseSuiteInfoVO;
import com.jmb.api.model.to.api.suite.ApiCaseSuiteTO;
import com.jmb.api.model.to.task.TaskTO;
import com.jmb.api.model.vo.api.suite.ApiCaseSuiteProcessorVO;
import com.jmb.api.model.vo.api.suite.ApiCaseSuiteVO;
import com.jmb.api.service.ApiCaseSuiteCaseRefService;
import com.jmb.api.service.ApiCaseSuiteProcessorService;
import com.jmb.api.service.ApiCaseSuiteService;
import com.jmb.api.mapper.ApiCaseSuiteMapper;
import com.jmb.api.vo.api.suite.ApiCaseSuiteVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
* @author jinbo
* @description 针对表【api_case_suite】的数据库操作Service实现
* @createDate 2025-04-08 13:53:56
*/
@Transactional
@Service
public class ApiCaseSuiteServiceImpl extends ServiceImpl<ApiCaseSuiteMapper, ApiCaseSuite>
    implements ApiCaseSuiteService{

    @Autowired
    private ApiCaseSuiteMapper apiCaseSuiteMapper;
    @Autowired
    private ApiCaseSuiteProcessorService processorService;
    @Autowired
    private ApiCaseSuiteCaseRefMapper caseSuiteCaseRefMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private ApiCaseSuiteCaseRefService caseSuiteCaseRefService;

    /**
     * 保存用例集
     * @param caseSuite 用例对象
     * @return 返回用例对象
     */
    @Override
    public ApiCaseSuite saveApiCaseSuite(ApiCaseSuite caseSuite) {
        this.save(caseSuite);
        return caseSuite;
    }

    /**
     * 保存用例集和处理器
     * @param apiCaseSuiteInfoTO 用例对象
     */
    @Override
    public void saveApiCaseSuiteAndProcessor(ApiCaseSuiteInfoTO apiCaseSuiteInfoTO) {
        // 先插入主表数据
        ApiCaseSuite apiCaseSuite = this.saveApiCaseSuite(apiCaseSuiteInfoTO);
        // 再插入子表数据
        List<ApiCaseSuiteProcessor> suiteProcessors = apiCaseSuiteInfoTO.getSuiteProcessors();
        if (suiteProcessors != null && !suiteProcessors.isEmpty()){
            suiteProcessors.forEach(suiteProcessor -> {
                apiCaseSuite.setSuiteId(suiteProcessor.getSuiteId());
                processorService.saveProcessor(suiteProcessor);
            });
        }

    }

    @Override
    public ApiCaseSuiteVo getApiCaseSuiteList(Integer suiteId) {
        LambdaQueryWrapper<ApiCaseSuite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApiCaseSuite::getSuiteId, suiteId);
        ApiCaseSuite apiCaseSuite = this.getOne(queryWrapper);
        ApiCaseSuiteVo apiCaseSuiteVo = new ApiCaseSuiteVo();
        BeanUtils.copyProperties(apiCaseSuite,apiCaseSuiteVo);
        return apiCaseSuiteVo;
    }

    @Override
    public void editApiCaseSuite(ApiCaseSuiteInfoTO suiteInfoTO) {
        // 修改主表
        LambdaUpdateWrapper<ApiCaseSuite> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApiCaseSuite::getSuiteId,suiteInfoTO.getSuiteId());
        this.update(updateWrapper);
        // 由于前端不方便传主键的ID，我这边删除子表数据，再重新插入子表数据
        Integer suiteId = suiteInfoTO.getSuiteId();
        processorService.removeApiCaseSuiteProcessorBySuiteId(suiteId);
        // 重新插入子表数据
        suiteInfoTO.getSuiteProcessors().forEach(suiteProcessor -> {
            suiteProcessor.setSuiteId(suiteId);
            processorService.saveProcessor(suiteProcessor);
        });



    }

    @Override
    public void removeApiCaseSuiteById(Integer suiteId) {
        // 存在测试用例的不准删除
        ApiCaseSuiteCaseRefTO apiCaseSuiteCaseRefTO = new ApiCaseSuiteCaseRefTO();
        apiCaseSuiteCaseRefTO.setSuiteId(suiteId);
        if (!caseSuiteCaseRefMapper.selectSuiteList(apiCaseSuiteCaseRefTO).isEmpty()){
            throw new LeaseException(ResultCodeEnum.WEB_API_CASE_SUITE_EXIST);
        }
        // 定时任务判断是否有任务
        TaskTO taskTO = new TaskTO();
        taskTO.setSuiteId(suiteId);
        if (!taskMapper.selectTaskList(taskTO).isEmpty()){
            throw new LeaseException(ResultCodeEnum.WEB_API_CASE_SUITE_TASK_EXIST);
        }
        // 删除主表数据
        this.removeById(suiteId);
        // 删除子表数据
        processorService.removeApiCaseSuiteProcessorBySuiteId(suiteId);
    }

    /**
     *
     * @param suiteId 用例集ID
     * @return 返回用例集对象
     */
    @Override
    public ApiCaseSuiteVO findApiCaseSuiteById(Integer suiteId) {
        if (suiteId== null){
            throw new LeaseException(ResultCodeEnum.WEB_API_ID_NOT_NULL);
        }
        LambdaQueryWrapper<ApiCaseSuite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApiCaseSuite::getSuiteId,suiteId);
        ApiCaseSuite apiCaseSuite = this.getOne(queryWrapper);
        ApiCaseSuiteVO apiCaseSuiteVO = new ApiCaseSuiteVO();
        BeanUtils.copyProperties(apiCaseSuite,apiCaseSuiteVO);
        return apiCaseSuiteVO;
    }

    /**
     * 根据用例集ID查询用例集信息
     * @param suiteId 用例集ID
     * @return 返回用例集信息
     */

    @Override
    public ApiCaseSuiteInfoVO findApiCaseSuiteInfoById(Integer suiteId) {
        return apiCaseSuiteMapper.selectApiCaseSuiteInfoById(suiteId);
    }

    /**
     * 分页查询
     * @param page 分页对象
     * @param apiCaseSuiteTO 查询条件
     * @return 返回分页数据
     */
    @Override
    public IPage<ApiCaseSuiteVO> findApiCaseSuiteList(IPage<ApiCaseSuiteVO> page, ApiCaseSuiteTO apiCaseSuiteTO) {
        return apiCaseSuiteMapper.selectApiCaseSuiteListPage(page,apiCaseSuiteTO);
    }

    /**
     * 查询所有用例集
     * @param apiCaseSuiteTO 查询条件
     * @return 返回用例集列表,不分页
     */
    @Override
    public List<ApiCaseSuiteVO> findApiCaseSuiteAll(ApiCaseSuiteTO apiCaseSuiteTO) {
        return apiCaseSuiteMapper.selectApiCaseSuiteList(apiCaseSuiteTO);
    }

    /**
     * 复制用例集
     * @param suiteId 用例集ID
     * @param creator 复制人
     * @return 返回用例集ID
     */
    @Override
    public HashMap<String, Integer> copyApiCaseSuiteById(Integer suiteId, String creator) {
        // 计数器
        AtomicReference<Integer> cpCount = new AtomicReference<>(0);
        // 1. 获取复制测试套件信息
        ApiCaseSuiteVO cpSuite = this.findApiCaseSuiteById(suiteId);
        // 2. 获取被测试套件下的所有测试用例
        List<ApiCaseSuiteCaseRef> cpSuiteCaseList = caseSuiteCaseRefMapper.selectSuiteAllCase(suiteId);
        // 3. 新增测试套件，获取新增测试套件编号
        ApiCaseSuite apiCaseSuite = new ApiCaseSuite();
        apiCaseSuite.setCreator(creator);
        BeanUtils.copyProperties(cpSuite,apiCaseSuite);
        ApiCaseSuite cpCaseSuite = this.saveApiCaseSuite(apiCaseSuite);
        // 4. 新增测试套件下的所有测试用例
        List<ApiCaseSuiteProcessorVO> cpSuiteProcessorList = processorService.findApiCaseSuiteProcessorBySuiteId(suiteId);
        cpSuiteProcessorList.forEach(suiteProcessor -> {
            ApiCaseSuiteProcessor cpSuiteProcessor = new ApiCaseSuiteProcessor();
            cpSuiteProcessor.setSuiteId(cpCaseSuite.getSuiteId());
            BeanUtils.copyProperties(suiteProcessor,cpSuiteProcessor);
            processorService.saveProcessor(cpSuiteProcessor);
        });
        // 5. 往新增测试套件测试用例
        LinkedList<ApiCaseSuiteCaseRef> toInsert = new LinkedList<>();
        cpSuiteCaseList.forEach(cpSuiteCase -> {
            cpSuiteCase.setSuiteId(cpCaseSuite.getSuiteId());
            toInsert.add(cpSuiteCase);
            cpCount.getAndSet(cpCount.get() + 1);
        });
        if (!toInsert.isEmpty()){
            caseSuiteCaseRefService.saveBatch(toInsert);
        }
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("cpSuiteCaseCount",cpCount.get());
        return hashMap;
    }
}




